import Reflux from 'reflux';
import PageConst from './PageConst';
import Actions from './Actions';
import update from 'react-addons-update';
import { Toast } from 'antd-mobile';
import Utils from '../../../utils/index'
import DB from '../../../app/db';
import StorageUtils from '../../../app/storage'
import { Control } from 'react-keeper'
import arrayTreeFilter from "array-tree-filter";

export default Reflux.createStore({
  listenables: [Actions],
  data: {
    ...PageConst,
    showWarn: false,
    warnTimer: null,
    codeTimer: null,
    warnMessage: '',
    count: 60,
    showCodeTimer: true,
    vcode: '',
    showCertOK:false,
    showPhoneOK:false,
    phone: '',
    sValue: [],
    zValue:[],
    showValue:[],
    seasons:[[]],
    seasonsValue: [],
    currentCour:{},
    userInfo: {
      id:'',
      name:'',
      phone:'',
      doors:[],
      courts:[],
      propris:[],
      state:'',
      priType:'',
      certNum: '',
      vcode: ''
    },
    info: {
      certNum: '请输入身份证号码',
      name: '',
      tel: '',
      court: {},
      editable: true
    }
  },

  init() {
    this.data.userInfo = update(this.data.userInfo, {$merge: {...StorageUtils.getUser()}});
    this.updateComponent();
  },

  initInfo() {
    let t = this;
    let proprietor = StorageUtils.getStorageItem('proprietor');
    if (proprietor && proprietor.id) {
      let info = {
        certNum: proprietor.identityCard,
        name: proprietor.name,
        tel: proprietor.phone,
        editable: false
      };
      t.data.info = update(t.data.info, {$merge: info});
      t.updateComponent();
    } else {
      let userInfo = StorageUtils.getUser();
      DB.WechatAPI.getProprietorByOpenId({openId: userInfo.openId}).then(
        function (content) {
          if (content && content.id) {
            StorageUtils.updateUser({proprietorId: content.id});
            StorageUtils.setStorage('proprietor', content);
            let info = {
              certNum: content.identityCard,
              name: content.name,
              tel: content.phone,
              editable: false
            };
            t.data.info = update(t.data.info, {$merge: info});
            t.updateComponent();
          }
        },
        function (error) {
          console.log(error);
        }
      );
    }
  },

  initMode: function () {
    let t = this;
    this.data.seasons = update(this.data.seasons, {$set: [[]]});
    this.data.seasonsValue = update(this.data.seasonsValue, {$set: []});
    this.data.zValue = update(this.data.zValue, {$set: []});
    this.data.propris = update(this.data.propris, {$set: []});
    this.data.userInfo = update(this.data.userInfo, {certNum: {$set: ''}});

    //this.onloadCourt();
  },

  initUser: function () {
    this.data.userInfo = update(this.data.userInfo, {$merge: {...StorageUtils.getStorage().get('user')}});
    this.updateComponent();
  },


  onChangeCurt: function (v) {
    this.data.zValue = update(this.data.zValue,  {$set: v});
    const value = v;
    if (!value) {
      return '';
    }
    const treeChildren = arrayTreeFilter(this.data.seasons[0], (c, level) => c.value === value[level]);
    let s = treeChildren.map(v => v.label).join(',');
    this.data.showValue = update(this.data.showValue,  {$set: [s]});

    this.updateComponent();
  },

  onSetCurt: function (e) {
    this.data.info = update(this.data.info, {court: {$set: e}});
    this.updateComponent();
  },

  onloadCourt: function () {

    let t = this;
    DB.WechatAPI.findCourtByPhone({
      phone: this.data.userInfo.phone,
    }).then(
      function (content) {
        let resultObj = Utils.isEmptyObject(content);
        if (resultObj.success) {
          t.data.courts = update(t.data.courts,  {$set: content});
          console.log(t.data.courts);
          t.data.courts.forEach(function(value,index,array){
            t.data.seasonsValue.push({
              label:value.name,
              value: value.id,
            })
          });
          t.data.seasons[0] = t.data.seasonsValue;
          t.updateComponent();
        }

      },
      function (error) {
        console.log(error);
      });
  },

  onCheckCertNum: function (e) {

    let t = this;
    let resultCertNum = Utils.checkCard(this.data.userInfo.certNum);
    if (!resultCertNum.success) {
      console.log(resultCertNum);
      this.showWarnMessage(e,resultCertNum.message);
      return;
    }

    if (resultCertNum.success) {
      DB.WechatAPI.checkUserCertNum({
        cert: this.data.userInfo.certNum,
      }).then(
        function (content) {
          let resultObj = Utils.isEmptyObject(content);
          console.info(resultObj.success);
          if (!resultObj.success) {
            t.showWarnMessage(e,'用户未注册');
          }
          else
          {
            t.data.userInfo = update(t.data.userInfo, {telNum: {$set: content.phone}});
            let resultPhone = Utils.checkPhone(t.data.userInfo.telNum);
            if (resultPhone.success) {
              t.data.showPhoneOK = update(t.data.showPhoneOK, {$set: true});
              t.data.showCertOK = update(t.data.showCertOK, {$set: true});
              t.data.userInfo = update(t.data.userInfo, {telNum: {$set: content.phone}});
              t.data.phone = update(t.data.phone,  {$set: t.data.userInfo.telNum});

              t.data.userInfo = update(t.data.userInfo, {phone: {$set: content.phone}});
              t.data.userInfo = update(t.data.userInfo, {name: {$set: content.name}});
              t.data.userInfo = update(t.data.userInfo, {state: {$set: content.state}});
              t.data.userInfo = update(t.data.userInfo, {priType: {$set: content.priType}});

              console.log(t.data.userInfo);
              StorageUtils.upUser(t.data.userInfo);

              DB.WechatAPI.binding(t.data.userInfo).then(
                function (content) {
                  Control.go('/home/my');
                },
                function (error) {
                  console.log(error);
                });

              t.updateComponent();
            }
            else {
              t.data.userInfo = update(t.data.userInfo, {phone: {$set: content.phone}});
              t.data.userInfo = update(t.data.userInfo, {name: {$set: content.name}});
              t.data.userInfo = update(t.data.userInfo, {state: {$set: content.state}});
              t.data.userInfo = update(t.data.userInfo, {priType: {$set: content.priType}});
              t.data.userInfo = update(t.data.userInfo, {id: {$set: content.id}});
              console.log('不严重');
              console.log(t.data.userInfo);
              StorageUtils.upUser(t.data.userInfo);
              Control.replace('/home/my');
            }

            console.log(content);

            t.updateComponent();
          }

        },
        function (error) {
          console.info('11_erro');
          console.log(error);
        });
    }
  },

  onEnterInfo: function (param) {
    let t = this;
    /*if (!param.court.id) {
      Toast.fail('小区未选择', 3);
      return false;
    }*/
    let certNum = this.data.info.certNum;
    if (!certNum && certNum === '') {
      Toast.fail('请输入身份证', 3);
      return false;
    }

    DB.WechatAPI.checkUserCard({
      card: certNum,
    }).then(
      function (content) {
        let resultObj = Utils.isEmptyObject(content);
        if (!resultObj.success) {
          Toast.fail('您提供的身份证没有找到房产信息', 2);
          // t.showWarnMessage(e,'用户未注册');
        } else {
          let params = {
            card: certNum,
            // courtId: param.court.id,
            openId: t.data.userInfo.openId
          };
          DB.WechatAPI.bindDoor(params).then(
            function (content) {
              DB.WechatAPI.binding({
                card: certNum,
                openId: t.data.userInfo.openId
              }).then(
                function (binding) {
                  Toast.fail('绑定小区成功', 2);
                  Control.replace('/home/my');
                },
                function (error) {
                  console.log(error);
                });
            },
            function (error) {
              console.log(error);
              alert(error.message);
            });
        }

      },
      function (error) {
        console.log(error);
        alert(JSON.stringify(error));
      });
  },

  showWarnMessage: function (e,message) {
    Toast.info(message, 1);
  },

  onChangeCertNum: function (certNum) {
    let info = this.data.info;
    info.certNum = certNum;
    this.data.info = update(this.data.info, {$set: info});
    this.updateComponent();
  },


  updateComponent: function () {
    this.trigger(this.data);
  },

  getInitialState: function () {
    return this.data;
  }
});
